package com.jpa.h2.controller;


import com.jpa.h2.model.Tutorial;
import com.jpa.h2.repository.TutorialRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class TutorialController {

    @Autowired
    private TutorialRepository tutorialRepository;

    /**
     *  根据title 查询（如果有返回对应数据，如果没有返回全部）
     *
     * @param title 文章标题
     * @return List<Tutorial>
     */
    @GetMapping("/tutorials")
    public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
        try {
            List<Tutorial> tutorialArrayList = new ArrayList<>();
            if (title == null) {
                tutorialRepository.findAll().forEach(tutorialArrayList::add);
            }else {
                tutorialRepository.findByTitleContaining(title).forEach(tutorialArrayList::add);
            }
            if (tutorialArrayList.isEmpty()) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
            return new ResponseEntity<>(tutorialArrayList, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据id 查询
     *
     * @param id id
     * @return Tutorial
     */
    @GetMapping("/tutorials/{id}")
    public ResponseEntity<Tutorial> getTutorialsById(@PathVariable("id") long id){
        Optional<Tutorial> tutorial = tutorialRepository.findById(id);
        if (tutorial.isPresent()) {
            return new ResponseEntity<>(tutorial.get(), HttpStatus.OK);
        }else
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    /**
     * 保存文章
     *
     * @param tutorial
     * @return Tutorial
     */
    @PostMapping("/tutorials")
    public ResponseEntity<Tutorial> createTutorial(@RequestBody() Tutorial tutorial){
        try {
            Tutorial save = tutorialRepository.save(new Tutorial(tutorial.getDescription(), tutorial.getTitle(), false));
            return new ResponseEntity<>(save, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 数据更新
     *
     * @param id id
     * @param tutorial tutorial
     * @return tutorial
     */
    @PutMapping("/tutorials/{id}")
    public ResponseEntity<Tutorial> updateTutorial(@PathVariable("id") long id, @RequestBody Tutorial tutorial){
        Optional<Tutorial> tutorialData = tutorialRepository.findById(id);
        if (tutorialData.isPresent()) {
            Tutorial _tutorial = tutorialData.get();
            _tutorial.setDescription(tutorial.getDescription());
            _tutorial.setTitle(tutorial.getTitle());
            _tutorial.setPublished(tutorial.isPublished());
            return new ResponseEntity<>(tutorialRepository.save(_tutorial), HttpStatus.OK);
        }else
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    /**
     * 根据id 删除
     *
     * @param id id
     * @return HttpStatus
     */
    @DeleteMapping("/tutorials/{id}")
    public ResponseEntity<HttpStatus> deleteTutorialById(@PathVariable("id") long id){
        try {
            tutorialRepository.deleteById(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 删除所有数据
     *
     * @return
     */
    @DeleteMapping("tutorials")
    public ResponseEntity<HttpStatus> deleteAllTutorial(){
        try {
            tutorialRepository.deleteAll();
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /***
     * 查询已发布的文章
     *
     * @return List
     */
    @GetMapping("/tutorials/published")
    public ResponseEntity<List<Tutorial>> getAllPublishedTutorials(){
        try {
            List<Tutorial> byPublished = tutorialRepository.findByPublished(true);
            if (byPublished.isEmpty()) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
            return new ResponseEntity<>(byPublished, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }
}
